Imports System.IO
Imports System.Data.OleDB
Imports System.Windows.Forms.VisualStyles

Module PublicFunction
    Public db As New Database

    Function Encode(ByVal dec As String) As String

        Dim bt() As Byte
        ReDim bt(dec.Length)
        bt = System.Text.Encoding.ASCII.GetBytes(dec)
        Dim enc As String
        enc = System.Convert.ToBase64String(bt)

        Return enc
    End Function

    Function Decode(ByVal enc As String) As String
        Dim bt() As Byte

        bt = System.Convert.FromBase64String(enc)
        Dim dec As String
        dec = System.Text.Encoding.ASCII.GetString(bt)
        Return dec
    End Function

    Public Function FileToByte(ByVal FileName As String) As Byte()
        Dim picture As Byte()
        If (Not File.Exists(FileName)) Then
            Return New Byte(0) {}
        End If

        Dim fs As FileStream = Nothing
        Try
            '#Region "Reading file"

            fs = New FileStream(FileName, FileMode.Open)
            ' Finding out the size of the file to be uploaded
            Dim fi As FileInfo = New FileInfo(FileName)
            Dim temp As Long = fi.Length
            Dim lung As Integer = Convert.ToInt32(temp)
            ' ------------------------------------------
            ' Reading the content of the file into an array of bytes.
            picture = New Byte(lung - 1) {}
            fs.Read(picture, 0, lung)
            fs.Close()
            ' ------------------------------------------
            '#End Region
            Return picture
        Catch e As Exception
            Console.WriteLine(e.Message & "	- " & e.StackTrace)
            Return New Byte(0) {}
        End Try
    End Function
    Public Function FillSpace(ByVal st As String, ByVal length As Integer, ByVal pec As Integer, ByVal kt As String, ByVal align As String) As String
        Dim out As String
        Dim i As Integer
        out = st
        If pec > 0 Then
            For i = 1 To length - Len(st) ' +1; cong them mot neu khong tinh dau .
                If UCase(align) = "LEFT" Then
                    out = kt & out
                Else
                    out = out & kt
                End If

            Next
            FillSpace = out
        Else
            For i = 1 To length - Len(st)
                If UCase(align) = "RIGHT" Then
                    out = out & kt
                Else
                    out = kt & out
                End If
            Next
            FillSpace = out
        End If
    End Function
    Public Function correctCard(ByVal card As String) As String
        Dim t As String = ""
        For i As Int16 = 0 To card.Length - 1

            If card(i) = Nothing Then
                Exit For
            End If
            t = t & card(i)
        Next
        Return t
    End Function
    Public Function getLastCard(ByVal sql As String) As String

        Dim ds As DataSet
        getLastCard = ""
        'Try
        db.iscardServer = True
        ds = db.getvalue(sql)
        'ds = db.getStoredProcedure("GetLastCard")
        If ds.Tables(0).Rows.Count > 0 Then
            getLastCard = correctCard(ds.Tables(0).Rows(0).Item("CardNo"))

            db.SetLastCard(ds.Tables(0).Rows(0).Item("RID"))
        End If
        db.iscardServer = False
        'Catch ex As Exception
        'db.iscardServer = False
        'End Try


    End Function

    'value: value can tim
    'flag: true: tim theo text; false: tim theo value
    Public Function FindIndex(ByVal ds As ComboBox, ByVal value As String, ByVal flag As Boolean) As Integer
        Dim i As Integer
        If ds Is Nothing Then
            Return -1
        End If

        For i = 0 To ds.Items.Count - 1
            If flag Then
                If CType(ds.Items(i), DataRowView).Item(1) = value Then
                    Return i
                End If
            Else
                If CType(ds.Items(i), DataRowView).Item(0) = value Then
                    Return i
                End If
            End If
        Next
        Return -1
    End Function
    Public Function LeftCoupon(ByVal EmployeeID As String) As Double
        'left=total-coupon
        '=Quarters.qLimit-Sum(Transactions.coupon.Scale*Transaction.tQuantity,Transaction.EmployeeID,timer)

        Dim coupon As Double
        coupon = "0" & db.getvalue("select sum(coupon.cscale*Transactions.tQuantity) as TotalCoupon from transactions,coupon where transactions.coupon = coupon.couponID and transactions.tdate between (select qStartDate from Quarters where getdate() between qstartDate and qEndDate) and (select qEndDate from Quarters where getdate() between qstartDate and qEndDate) and transactions.EmployeeID = '" & EmployeeID & "'", "totalCoupon")
        Return Math.Round(qlimit(EmployeeID) - coupon, 2)
    End Function
    Public Function qLimit(ByVal EmployeeID As String) As Double
        Dim limit As Double
        Dim st As String
        Try
            st = db.getvalue("select * from ECoupon where cemployeeID = '" & EmployeeID & "'", "cMax")
            st = IIf(st.Length = 0, "0", st)
            limit = CType(st, Double)
        Catch ex As Exception
            limit = 0
        End Try

        If Math.Round(limit, 2) = 0 Then
            limit = db.getvalue("select * from Quarters where getdate() between qstartDate and qEndDate ", "Qlimit")
        End If
        Return limit
    End Function
    Public Function LeftC(ByVal employee As String, ByVal couponid As String, ByVal quantity As Integer) As String
        Dim t As String
        t = Math.Round(LeftCoupon(employee) - db.getvalue("select * from coupon where couponID='" & couponid & "'", "CScale") * quantity, 2)
        Dim limit As String
        limit = db.getvalue("select * from employee where employeeid = '" & employee & "'", "elimit")

        If Not CType(IIf(limit.Length <= 0, True, limit), Boolean) Then
            t = "No limit"
        End If
        Return t
    End Function
    Public Function TotalOfDay(ByVal employee As String) As Integer
        Return db.getvalue("select count(*) as total from transactions where year(tdate) = year(getdate()) and month(tdate) = month(getdate()) and day(tdate) = day(getdate()) and employeeid = '" & employee & "'", "Total")
    End Function
    Public Function checkQuarterDate(ByVal sdate As Date, ByVal edate As Date, ByVal QuarterID As String) As Boolean
        If sdate.CompareTo(edate) > 0 Then Return False
        Dim sql As String
        Dim ds As DataSet
        sql = "select * from Quarters where QuarterID <> '" & QuarterID & "' and (qStartDate between '" & sdate & "' and '" & edate & "'" _
            & " or qEndDate between '" & sdate & "' and '" & edate & "'" _
            & " or '" & sdate & "' between qStartDate and qEndDate or '" & edate & "' between qStartDate and qEndDate)"
        ds = db.getvalue(sql)
        If ds.Tables(0).Rows.Count > 0 Then Return False
        Return True
    End Function
    Public Function checkCouponTime(ByVal btime As Date, ByVal etime As Date, ByVal couponID As String) As Boolean
        Dim b, e As Integer
        b = btime.Hour * 3600 + btime.Minute * 36 + btime.Second
        e = etime.Hour * 3600 + etime.Minute * 36 + etime.Second

        If b.CompareTo(e) > 0 Then Return False
        Dim sql As String
        Dim ds As DataSet
        sql = "select * from Coupon where CouponID <> '" & couponID & "' and " _
        & "( " & b & " between datepart(hour,cbtime)*3600+datepart(minute,cbtime)*36+ " _
        & "datepart(second,cbtime) and datepart(hour,cetime)*3600+datepart(minute,cetime)*36+ " _
        & "datepart(second,cetime) or " & e & " between datepart(hour,cbtime)*3600+datepart(minute,cbtime)*36+ " _
        & "datepart(second,cbtime) and datepart(hour,cetime)*3600+datepart(minute,cetime)*36+ " _
        & "DatePart(Second, cetime)" _
        & "or datepart(hour,cbtime)*3600+datepart(minute,cbtime)*36+ " _
        & "datepart(second,cbtime) between " & b & " and " & e & " or datepart(hour,cetime)*3600+datepart(minute,cetime)*36+ " _
        & "datepart(second,cetime) between " & b & " and " & e & " )"
        ds = db.getvalue(sql)
        If ds.Tables(0).Rows.Count > 0 Then Return False
        Return True
    End Function
    Public Function DisplayCoupon() As String
        Return db.getvalue("select * from coupon where datepart(hour,getdate())*3600+datepart(minute,getdate())*36 +datepart(second,getdate()) between datepart(hour,cbtime)*3600+datepart(minute,cbtime)*36 +datepart(second,cbtime) and datepart(hour,cetime)*3600+datepart(minute,cetime)*36+ datepart(second,cetime)", "couponid")
    End Function
    Public Function setOptions(ByVal Name As String, ByVal value As String) As Boolean
        Try
            db.update("update options set ovalue = '" & value & "' where oname = '" & Name & "'")
        Catch ex As Exception
            Return False
        End Try
        Return True
    End Function
    Public Function getOptions(ByVal Name As String) As String
        Try
            Return db.getvalue("select * from options where oname = '" & Name & "'", "ovalue")
        Catch ex As Exception
            Return ""
        End Try

    End Function
    Public Function getLastCardSQL() As String
        Try
            Return db.getvalue("select * from StoredProcedure where sid='getlastcard'", "svalue")
        Catch ex As Exception
            Return ""
        End Try
    End Function
    Function formatErrors(ByVal st As String, ByVal font As Byte) As String
        Dim l As Byte ' So ky tu tren mot dong
        Dim i As Integer
        Dim s, sl As String
        If font = 0 Then
            l = 33
        Else
            l = 40
        End If

        s = Mid$(st, 1, l)
        sl = ""
        Do While Len(s) > 0
            i = 0
            If Len(s) > l * 2 / 3 Then ' neu chieu dai mot chuoi lon hon 2/3 l
                For i = Len(s) To 1 Step -1 'tim khoang trang de chen ky tu enter
                    If Mid(s, i, 1) = " " Then ' neu tim thay
                        sl = sl & Mid$(st, 1, i) & Chr(13) & Chr(10) 'chen ky tu enter
                        Exit For
                    End If
                Next
            End If

            If i = 0 Then 'neu khong tim thay
                sl = sl & s & Chr(13) & Chr(10) ' lay bay chieu dai l
                st = Mid$(st, l + 1)
            Else
                st = Mid$(st, i + 1) ' loai bo chuoi ky tu da xu ly
            End If

            s = Mid$(st, 1, l) 'lay chuoi ky tu moi
        Loop
        formatErrors = sl

    End Function
End Module
Public Class DataGridViewDisableButtonColumn
    Inherits DataGridViewButtonColumn

    Public Sub New()
        Me.CellTemplate = New DataGridViewDisableButtonCell()
    End Sub
End Class

Public Class DataGridViewDisableButtonCell
    Inherits DataGridViewButtonCell
    Private enabledValue As Boolean
    Public Property Enabled() As Boolean
        Get
            Return enabledValue
        End Get
        Set(ByVal value As Boolean)
            enabledValue = value
        End Set
    End Property

    ' Override the Clone method so that the Enabled property is copied.
    Public Overrides Function Clone() As Object
        Dim Cell As DataGridViewDisableButtonCell = _
            CType(MyBase.Clone(), DataGridViewDisableButtonCell)
        Cell.Enabled = Me.Enabled
        Return Cell
    End Function

    ' By default, enable the button cell.
    Public Sub New()
        Me.enabledValue = True
    End Sub

    Protected Overrides Sub Paint(ByVal graphics As Graphics, _
        ByVal clipBounds As Rectangle, ByVal cellBounds As Rectangle, _
        ByVal rowIndex As Integer, _
        ByVal elementState As DataGridViewElementStates, _
        ByVal value As Object, ByVal formattedValue As Object, _
        ByVal errorText As String, _
        ByVal cellStyle As DataGridViewCellStyle, _
        ByVal advancedBorderStyle As DataGridViewAdvancedBorderStyle, _
        ByVal paintParts As DataGridViewPaintParts)

        ' The button cell is disabled, so paint the border,  
        ' background, and disabled button for the cell.
        If Not Me.enabledValue Then

            ' Draw the background of the cell, if specified.
            If (paintParts And DataGridViewPaintParts.Background) = _
                DataGridViewPaintParts.Background Then

                Dim cellBackground As New SolidBrush(cellStyle.BackColor)
                graphics.FillRectangle(cellBackground, cellBounds)
                cellBackground.Dispose()
            End If

            ' Draw the cell borders, if specified.
            If (paintParts And DataGridViewPaintParts.Border) = _
                DataGridViewPaintParts.Border Then

                PaintBorder(graphics, clipBounds, cellBounds, cellStyle, _
                    advancedBorderStyle)
            End If

            ' Calculate the area in which to draw the button.
            Dim buttonArea As Rectangle = cellBounds
            Dim buttonAdjustment As Rectangle = _
                Me.BorderWidths(advancedBorderStyle)
            buttonArea.X += buttonAdjustment.X
            buttonArea.Y += buttonAdjustment.Y
            buttonArea.Height -= buttonAdjustment.Height
            buttonArea.Width -= buttonAdjustment.Width

            ' Draw the disabled button.                
            ButtonRenderer.DrawButton(graphics, buttonArea, _
                PushButtonState.Disabled)

            ' Draw the disabled button text. 
            If TypeOf Me.FormattedValue Is String Then
                TextRenderer.DrawText(graphics, CStr(Me.FormattedValue), _
                    Me.DataGridView.Font, buttonArea, SystemColors.GrayText)
            End If

        Else
            ' The button cell is enabled, so let the base class 
            ' handle the painting.
            MyBase.Paint(graphics, clipBounds, cellBounds, rowIndex, _
                elementState, value, formattedValue, errorText, _
                cellStyle, advancedBorderStyle, paintParts)
        End If
    End Sub
End Class